home *** CD-ROM | disk | FTP | other *** search
/ CU Amiga Super CD-ROM 19 / CU Amiga Magazine's Super CD-ROM 19 (1998)(EMAP Images)(GB)[!][issue 1998-02].iso / CUCD / Programming / LEDA / source / src / graph_alg / _components.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-11-16  |  1.8 KB  |  92 lines

  1. /*******************************************************************************
  2. +
  3. +  LEDA  3.1c
  4. +
  5. +
  6. +  _components.c
  7. +
  8. +
  9. +  Copyright (c) 1994  by  Max-Planck-Institut fuer Informatik
  10. +  Im Stadtwald, 6600 Saarbruecken, FRG     
  11. +  All rights reserved.
  12. *******************************************************************************/
  13.  
  14.  
  15. /*******************************************************************************
  16. *                                                                              *
  17. *  COMPONENTS  (connected components)                                          *
  18. *                                                                              *
  19. *******************************************************************************/
  20.  
  21.  
  22. #include <LEDA/graph_alg.h>
  23.  
  24. #include <LEDA/node_partition.h>
  25.  
  26. static int count;
  27.  
  28. static void dfs(node v, node_array<int>& compnum)
  29.   node_stack  S;
  30.  
  31.   S.push(v);
  32.   compnum[v] = count;
  33.  
  34.   while (!S.empty())
  35.    { v = S.pop(); 
  36.      node w;
  37.      forall_adj_nodes(w,v) 
  38.         if (compnum[w] == -1)
  39.         { compnum[w] = count;
  40.           S.push(w);
  41.          }
  42.     }
  43.  
  44.  
  45. int COMPONENTS(const ugraph& G, node_array<int>& compnum)
  46. { // computes connected components of undirected graph G
  47.   // compnum[v] = i  iff v in component i
  48.   // number of components is returned
  49.  
  50.   node v;
  51.  
  52.   forall_nodes(v,G) compnum[v] = -1;
  53.  
  54.   count = 0;
  55.  
  56.   forall_nodes(v,G) 
  57.     if (compnum[v] == -1) 
  58.     { dfs(v,compnum);
  59.       count++; 
  60.      }
  61.  
  62.   return count;
  63. }
  64.  
  65.  
  66.  
  67. int COMPONENTS1(const ugraph& G, node_array<int>& compnum)
  68.  
  69.   node_partition P(G);
  70.   edge e;
  71.   node v;
  72.  
  73.   forall_nodes(v,G) compnum[v] = -1;
  74.  
  75.   forall_edges(e,G) P.union_blocks(source(e),target(e));
  76.  
  77.   int count = 0;
  78.   forall_nodes(v,G) 
  79.    { node w = P.find(v);
  80.      if (compnum[w]==-1) compnum[w] = count++;
  81.      compnum[v] = compnum[w];
  82.     }
  83.  
  84.   return count;
  85. }
  86.  
  87.  
  88.